package com.monodev.mvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by Administrator on 2017/11/21 0021.
 */
@Controller
public class UploadController {
    @RequestMapping("/uploadImage")
    public ModelAndView upload(HttpServletRequest request) {    //接受上传文件，保存到服务器
        String name = "您上传的文件" + ".jpg";
        MultiValueMap<String, MultipartFile> multiFileMap = ((DefaultMultipartHttpServletRequest) request).getMultiFileMap();
        MultipartFile yourImage = (MultipartFile) ((LinkedMultiValueMap) multiFileMap).getFirst("image");

        File newFile = new File(request.getServletContext().getRealPath("")+"/WEB-INF/images", name);  //地址，文件名，差文件内容
        newFile.getParentFile().mkdirs();
        try {
            yourImage.transferTo(newFile);
            return new ModelAndView("OKOK");
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
